package it.unisalento.appsalento.activity.fragment;

import it.unisalento.R;
import it.unisalento.appsalento.activity.App;
import it.unisalento.appsalento.model.Appello;
import it.unisalento.calendar.CalendarAdapter;
import it.unisalento.util.DateUtils;

import java.util.ArrayList;
import java.util.Calendar;

import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.TextView;

public class CalendarioFragment extends Fragment {

	public Calendar month;
	public CalendarAdapter adapter;
	public Handler handler;
	public ArrayList<String> items; // container to store some random calendar
	
	public static final String ARG_PLANET_NUMBER = "planet_number";

	ArrayAdapter<String> sd;

	public int TOTAL_LIST_ITEMS = 0;
	public int NUM_ITEMS_PAGE = 0;
	LayoutInflater inflaterFragment;
	public CalendarioFragment() {
		// Empty constructor required for fragment subclasses
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.fragment_calendario,container, false);
		
		month = Calendar.getInstance();
		// onNewIntent(getIntent());

		items = new ArrayList<String>();
		adapter = new CalendarAdapter(rootView.getContext(), month);

//		mCalendarTask = new CalendarTask();
//		mCalendarTask.execute((Void) null);
		
		GridView gridview = (GridView) rootView.findViewById(R.id.gridview);
		gridview.setAdapter(adapter);

		handler = new Handler();
		handler.post(calendarUpdater);

		TextView title = (TextView) rootView.findViewById(R.id.title);
		title.setText(android.text.format.DateFormat.format("MMMM yyyy", month));

		TextView previous = (TextView) rootView.findViewById(R.id.previous);
		previous.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (month.get(Calendar.MONTH) == month.getActualMinimum(Calendar.MONTH)) {
					month.set((month.get(Calendar.YEAR) - 1),
							month.getActualMaximum(Calendar.MONTH), 1);
				} else {
					month.set(Calendar.MONTH, month.get(Calendar.MONTH) - 1);
				}
				refreshCalendar();
			}
		});

		TextView next = (TextView) rootView.findViewById(R.id.next);
		next.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (month.get(Calendar.MONTH) == month.getActualMaximum(Calendar.MONTH)) {
					month.set((month.get(Calendar.YEAR) + 1),
					month.getActualMinimum(Calendar.MONTH), 1);
				} else {
					month.set(Calendar.MONTH, month.get(Calendar.MONTH) + 1);
				}
				refreshCalendar();

			}
		});

		gridview.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View v,int position, long id) {
				TextView date = (TextView) v.findViewById(R.id.date);
				if (date instanceof TextView && !"".equals(date.getText())) {
					String day = date.getText().toString();
					if(items.contains(day)){
//						Dialog dialog = new Dialog(v.getContext());
//		                dialog.setContentView(R.layout.fragment_giorno_calendario);
//		                dialog.setTitle(day +"-"+ android.text.format.DateFormat.format("MM-yyyy",month) );
//		                dialog.setCancelable(true);
//		                ListView listView = (ListView) dialog.getWindow().findViewById(R.id.listViewAppello);
							
						ArrayList<Appello> listaAppelliToView = new ArrayList<Appello>();
						
						month.set(Calendar.DAY_OF_MONTH,Integer.parseInt(day));
						Calendar calendar = DateUtils.setCalendarTimeZero(month);
 						for(Appello row : App.appelli){
 							
 							Calendar calendarScritto = DateUtils.setDateTimeZero(row.getDataProvaScritta());
 							Calendar calendarOrale = DateUtils.setDateTimeZero(row.getDataProvaOrale());
 							if(calendarOrale.equals(calendar) || calendarScritto.equals(calendar) ){
 								listaAppelliToView.add(row);
 							}	
 						}	
 						App.appelliForDay =  listaAppelliToView;
 						FragmentManager fragmentManager = getFragmentManager();
 						fragmentManager.beginTransaction().replace(R.id.content_frame, new GiornoCalendarioFragment()).addToBackStack(null)
 								.commit();
				       
// 						AppelliCalendarioAdapter adapter = new AppelliCalendarioAdapter(getActivity(), R.layout.row_appello_calendario, listaAppelliToView);
// 						adapter.notifyDataSetChanged();
// 						listView.setAdapter(adapter);
// 						listView.setOnItemClickListener(new OnItemClickListener() {
// 							public void onItemClick(AdapterView<?> parent, View v,
// 									int position, long id) {
// 								Appello appello = (Appello) parent.getItemAtPosition(position);
//
// 								Dialog dialog = new Dialog(parent.getContext());
// 								dialog.setContentView(R.layout.row_dettaglio_appello);
// 								dialog.setTitle(appello.getNomeEsame());
// 								AppelloAdapter appelloAdapter = new AppelloAdapter();
// 								appelloAdapter.setAppello(appello, dialog,(MainActivity)getActivity());
//
// 								dialog.setCancelable(true);
// 								dialog.show();
// 							}
//
//							
// 						});
 						
//		                dialog.show();
					}

				}

			}
		});
		return rootView;
	}

	public void refreshCalendar() {
		TextView title = (TextView) getView().findViewById(R.id.title);

		adapter.refreshDays();
		adapter.notifyDataSetChanged();
		handler.post(calendarUpdater); // generate some random calendar items

		title.setText(android.text.format.DateFormat.format("MMMM yyyy", month));
	}

	public void onNewIntent(Intent intent) {
		String date = intent.getStringExtra("@+id/date");
		String[] dateArr = date.split("-"); // date format is yyyy-mm-dd
		month.set(Integer.parseInt(dateArr[0]), Integer.parseInt(dateArr[1]),
				Integer.parseInt(dateArr[2]));
	}

	public Runnable calendarUpdater = new Runnable() {

		@Override
		public void run() {
			items.clear();
			// format random values. You can implement a dedicated class to
			// provide real values
			for(Appello appello :  App.appelli){
				if(appello.getDataProvaOrale() != null){
					if(DateUtils.isRightMonth(month, appello.getDataProvaOrale())){
						
						items.add(Integer.toString(DateUtils.getDayFromDate(appello.getDataProvaOrale())));
				
					}
					if(DateUtils.isRightMonth(month, appello.getDataProvaScritta())){
						items.add(Integer.toString(DateUtils.getDayFromDate(appello.getDataProvaScritta())));
					}
				}
			}

			adapter.setItems(items);
			adapter.notifyDataSetChanged();
		}
	};
	
	
}
